#import "LSLHSBWhitePicker.h"
///////////////////////////////////////
/**       LSLColorCicle七彩色环       */
///////////////////////////////////////
@interface LSLWhiteCicle : UIView

@end

@implementation LSLWhiteCicle
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {//获取父类的参数
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.layer.cornerRadius = self.frame.size.width * 0.5;
}

- (void)drawRect:(CGRect)rect
{
    CGFloat layerWH = self.frame.size.width - 30;
    CALayer *contentLayer = [CALayer layer];
    [self.layer addSublayer:contentLayer];
    contentLayer.frame = CGRectMake(15, 15, self.frame.size.width - 30, self.frame.size.height - 30);
    contentLayer.backgroundColor = [UIColor blueColor].CGColor;
    //创建圆环
    CGFloat lineWidth = 10;
    CGFloat radius = layerWH * 0.5 - lineWidth * 0.5;
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(layerWH * 0.5, layerWH * 0.5) radius:radius startAngle:- M_PI/3 endAngle:M_PI + M_PI /3 clockwise:YES];
    //圆环遮罩
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor whiteColor].CGColor;
    shapeLayer.lineWidth = lineWidth;
    shapeLayer.strokeStart = 0;
    shapeLayer.strokeEnd = 1;
    shapeLayer.lineCap = kCALineCapRound;
    shapeLayer.lineDashPhase = 0.8;
    shapeLayer.path = bezierPath.CGPath;
    [contentLayer setMask:shapeLayer];
    
    NSMutableArray *colors = [NSMutableArray arrayWithObjects:(id)[UIColor orangeColor].CGColor,(id)[UIColor colorWithRed:255.0/255.0 green:165.0/255.0 blue:0.0 alpha:1.0].CGColor, nil];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.shadowPath = bezierPath.CGPath;
    gradientLayer.frame = CGRectMake(0, 0, layerWH * 0.5, layerWH);
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1);
    [gradientLayer setColors:[NSArray arrayWithArray:colors]];

    NSMutableArray *colors1 = [NSMutableArray arrayWithObjects:(id)[UIColor whiteColor].CGColor,(id)[UIColor colorWithRed:255.0/255.0 green:165.0/255.0 blue:0.0 alpha:1.0].CGColor, nil];
    CAGradientLayer *gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.shadowPath = bezierPath.CGPath;
    gradientLayer1.frame = CGRectMake(layerWH * 0.5, 0, layerWH * 0.5, layerWH);
    gradientLayer1.startPoint = CGPointMake(1, 0);
    gradientLayer1.endPoint = CGPointMake(1, 1);
    [gradientLayer1 setColors:[NSArray arrayWithArray:colors1]];

    [contentLayer addSublayer:gradientLayer]; //设置颜色渐变
    [contentLayer addSublayer:gradientLayer1];
}
@end
///////////////////////////////////////
/**       LSLCenterCircleView        */
///////////////////////////////////////
@interface LSLWhiteCenterCircleView : UIView

@property (nonatomic, strong) UIView *colorView;
@property (nonatomic, strong) UIColor *centerCircleColor;

@end

@implementation LSLWhiteCenterCircleView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _centerCircleColor = [UIColor orangeColor];
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:_colorView];
    }
    return self;
}

- (void)setCenterCircleColor:(UIColor *)centerCircleColor {
    _centerCircleColor = centerCircleColor;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, self.centerCircleColor.CGColor);
    CGRect frame = CGRectMake(5,5,rect.size.width - 10,rect.size.height - 10);
    CGContextAddEllipseInRect(context, frame);
    CGContextFillPath(context);
}
@end
///////////////////////////////////////
/**   LSLDripView  指示器滑块          */
///////////////////////////////////////
@interface LSLWhiteDripView : UIView

@property (nonatomic, strong) UIView *dripView;
@property (nonatomic, strong) UIColor *dripCircleColor;

@end

@implementation LSLWhiteDripView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _dripCircleColor = [UIColor orangeColor];
        self.backgroundColor = [UIColor clearColor];
        
        [self addSubview:_dripView];
    }
    return self;
}

- (void)setDripCircleColor:(UIColor *)dripCircleColor {
    _dripCircleColor = dripCircleColor;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, self.dripCircleColor.CGColor);
    CGRect frame = CGRectMake(0,0,rect.size.width,rect.size.height );
    CGContextAddEllipseInRect(context, frame);
    CGContextAddLineToPoint(context, 0, 0);
    CGContextFillPath(context);
}
@end
///////////////////////////////////////
/**                 连接线         *////
///////////////////////////////////////
@interface DrawWhiteLineView : UIView

@property (nonatomic, strong) UIView *LineView;
@property (nonatomic, assign) CGPoint dripViewCenter;
@property (nonatomic, assign) CGPoint colorCircleViewCenter;

@end

@implementation DrawWhiteLineView
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)setDripViewCenter:(CGPoint)dripViewCenter{
    _dripViewCenter = dripViewCenter;
    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGMutablePathRef path =  CGPathCreateMutable();
    CGContextMoveToPoint(ctx, self.dripViewCenter.x, self.dripViewCenter.y);
    CGContextAddLineToPoint(ctx,self.colorCircleViewCenter.x, self.colorCircleViewCenter.y);
    CGContextAddPath(ctx, path);
    CGContextStrokePath(ctx);
}
@end
//////////////////////////////////////////////////
/**             LSLHSBColorPickerView           */
//////////////////////////////////////////////////
typedef void(^ColorSelectedBlock)(UIColor *, BOOL);

@interface LSLHSBWhitePicker ()
@property (nonatomic, copy) ColorSelectedBlock colorSelectedBlock;
@property (nonatomic, getter=isConfirm) BOOL confirm;

@property (nonatomic, strong) UIColor *color;
@property (nonatomic, assign) CGFloat hue;
@property (nonatomic, assign) CGFloat flag;

@property (nonatomic, assign) CGFloat saturation;
@property (nonatomic, assign) CGFloat brightness;
@property (nonatomic, assign) CGFloat alpha;
@property (nonatomic, strong) UIView *colorCircleView;
@property (nonatomic, strong) LSLWhiteCenterCircleView *centerCircleView;
@property (nonatomic, strong) LSLWhiteCicle *colorView;//色环
@property (nonatomic, strong) UIButton *dripBtn;
@property (nonatomic, strong) LSLWhiteDripView *dripView;
@property (nonatomic, assign) CGFloat radius;
@property (nonatomic, assign) CGFloat dripViewX;
@property (nonatomic, strong) DrawWhiteLineView *lineView;
@property (nonatomic, assign) CGPoint dripViewCenter;

@end

static CGFloat DripViewWidthAndHeight = 30;//指示器滑块的直径

@implementation LSLHSBWhitePicker

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initialize];
    }
    return self;
}

- (void)initialize
{
    _hue = 1.0;//色调
    _saturation = 1.0;//饱和度
    _brightness = 1.0;//亮度
    _alpha = 1.0;//透明度
    
    _colorCircleView = [[UIView alloc] init];//放置色环的视图
    
    _colorView = [[LSLWhiteCicle alloc] init];//色环的外接圆角矩形
    [_colorCircleView addSubview:_colorView];//调用layoutSubviews
    
    _lineView = [[DrawWhiteLineView alloc] init];
    [_colorCircleView addSubview:_lineView];//
    
    _centerCircleView = [[LSLWhiteCenterCircleView alloc] init];
    [_colorCircleView addSubview:_centerCircleView];
    
    _dripView  = [[LSLWhiteDripView alloc] init];
    
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changedPositionAndColor:)];
    [_dripView addGestureRecognizer:panRecognizer];
        [_colorCircleView addSubview:_dripView];
    
    _dripBtn = [[UIButton alloc] initWithFrame:_dripView.bounds];
    [_dripView addSubview:_dripBtn];
    [_dripView bringSubviewToFront:_dripBtn];//将Btn显示在最前面
    [self addSubview:_colorCircleView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGSize size              = self.frame.size;
    CGFloat square           = fmin(size.height, size.width);//获取短的一边（width）
    size                     = CGSizeMake(square - 20, square -20);//放置色环的视图//以短边形成的正方形
    CGFloat x                = (self.frame.size.width - size.width) * 0.5; //等于0
    _radius                  = size.width * 0.5;//短边的一半
    _dripViewX               = _radius - DripViewWidthAndHeight * 0.7;//指示器滑块的轨道半径
    CGFloat radiusCenter     = (size.width - 24) *0.25;//中心小圆的直径
    
    
    _colorCircleView.frame   = CGRectMake(x, x, size.width, size.height);//放置色环的视图
    
    _colorView.frame         = CGRectMake(0, 0, size.width, size.height); //色环
    _lineView.frame          = CGRectMake(0, 0, size.width, size.height);
    _centerCircleView.frame  = CGRectMake(0,0 , radiusCenter , radiusCenter);
    _centerCircleView.center = CGPointMake(_radius, _radius);
    _dripView.frame          = CGRectMake(100, 100, DripViewWidthAndHeight, DripViewWidthAndHeight);
    _dripBtn.frame          = _dripView.bounds;
    self.lineView.colorCircleViewCenter = _centerCircleView.center;
    self.lineView.dripViewCenter        = [self changeDripViewPositionWithDuration];
}

- (void)changedPositionAndColor:(UIGestureRecognizer *)recognizer{
//    if(!(_hue>0&&_hue<1.0/6.0)){
    CGPoint point = [recognizer locationInView:_colorCircleView];
    
    CGFloat dx = point.x - self.radius;
    CGFloat dy = point.y - self.radius;

    CGFloat angle = atan2f(dy, dx);
    angle += M_PI / 3 * 2;
    _hue = angle / (2 * M_PI);
//    }else{
//        CGPoint point = [recognizer locationInView:_colorCircleView];
//        CGFloat dx = point.x - self.radius;
//        if(dx<0){
//            _hue = -0.001;
//        }
//        else{
//            _hue = 1.0/6.0+0.001;
//        }
//    }
        [self changeValue];
    
}

- (UIColor *)changeColor{
    self.centerCircleView.centerCircleColor = _color;
    self.dripView.dripCircleColor = _color;
    [self revertSelectedColorByBlock];

    return _color;
}

- (void)changeValue{
    //change color and dripcenter
    _dripViewCenter = [self changeDripViewPositionWithDuration];
    _color = [self colorOfPoint:_dripViewCenter];
    [self changeColor];
    self.lineView.dripViewCenter = _dripViewCenter;
  
}

- (CGPoint)changeDripViewPositionWithDuration{
    CGFloat leftAngle = - M_PI / 3 * 2;
    CGFloat rightAngle = - M_PI / 3 ;
    CGFloat currentAngle = M_PI * 2 * _hue - M_PI / 3 * 2;
    
    
if(!(currentAngle>leftAngle&&currentAngle<rightAngle)){
    CGFloat cx           = self.dripViewX * cos(currentAngle) + self.dripViewX +6;
    CGFloat cy           = self.dripViewX * sin(currentAngle) + self.dripViewX +6;
    CGRect frame         = self.dripView.frame;
    frame.origin.x       = cx;
    frame.origin.y       = cy;
    self.dripView.frame  = frame;
    // dripView shadow
    CGFloat offsetX      = 2 * cos(currentAngle);
    CGFloat offsetY      = 2 * sin(currentAngle + M_PI);
    self.dripView.layer.shadowOffset  = CGSizeMake(offsetX, offsetY);
    self.dripView.layer.shadowRadius  = 4;
    self.dripView.layer.shadowOpacity = 0.2;
   }

    return self.dripView.center;
}

//获取图片某一点的颜色
- (UIColor *)colorOfPoint:(CGPoint)point {
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    CGContextTranslateCTM(context, -point.x, -point.y);
    [_colorView.layer renderInContext:context];
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
    return color;
}


#pragma mark - block

- (void)colorSelectedBlock:(void (^)(UIColor *, BOOL))colorSelectedBlock {
    if (colorSelectedBlock) {
        self.colorSelectedBlock = colorSelectedBlock;
    }
}

- (void)revertSelectedColorByBlock {
    if (self.colorSelectedBlock) {
        self.colorSelectedBlock(self.color, self.isConfirm);
    }
}



@end
